/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controllers.sysAdmin;

import controllers.changePassword.RandomPassword;
import models.User;
import controllers.utils.DatabaseHjelper;
import controllers.utils.SendMail;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Named;
//import javax.faces.bean.SessionScoped;
import javax.enterprise.context.SessionScoped;

/**
 *
 * @author dybvik
 */
@SessionScoped
@Named(value="userList")
public class UserList implements Serializable{
    private final List<User> users = new ArrayList<User>();
    private final DatabaseHjelper dbh = DatabaseHjelper.hent();

    /** Creates a new instance of UserList */
    public UserList() {
    }

    public String navToUserList(){
        updateUsers();
        return "userList";
    }

    private void updateUsers() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = dbh.finnForbindelse();
            stmt = conn.prepareStatement("select * from users");
            res = stmt.executeQuery();
            synchronized (users) {
                users.clear();
                while (res.next()){
                    User u = new User(res.getInt("userID"), res.getString("userName"), res.getString("userFirstName"), res.getString("userLastName"), res.getString("email"), res.getString("password"), res.getDate("dateRegistered"), res.getDate("dateLastLoggedIn"));
                    users.add(u);
                }
                stmt = conn.prepareStatement("select * from userRole");
                res = stmt.executeQuery();
                while (res.next()){
                    String userName = res.getString("userName");
                    String role = res.getString("role");
                    for(User u: users){
                        if(u.getUserName().equals(userName)) u.setRole(role);
                    }
                }
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            DatabaseHjelper.lukk(res);
            DatabaseHjelper.lukk(stmt);
            DatabaseHjelper.lukk(conn);
        }
    }

    public void executeChanges() {
        for (User u : users) {
            if (u.isEditable()) {
                saveChanges(u);
                u.setEditable(false);
            }
        }
    }

    private void saveChanges(User u) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = dbh.finnForbindelse();
            stmt = conn.prepareStatement("update users set userName=?, userFirstName=?, userLastName=?, password=?, email=?  WHERE userID=?");
            stmt.setString(1, u.getUserName());
            stmt.setString(2, u.getFirstName());
            stmt.setString(3, u.getLastName());
            stmt.setString(4, u.getPassword());
            stmt.setString(5, u.getEmail());
            stmt.setInt(6, u.getUserID());
            stmt.executeUpdate();
            stmt = conn.prepareStatement("DELETE FROM userRole WHERE userName=?");
            stmt.setString(1, u.getUserName());
            stmt.executeUpdate();
            for(String s: u.getRoles()){
                stmt = conn.prepareStatement("INSERT INTO userRole(userName, role) VALUES(?, ?)");
                stmt.setString(1, u.getUserName());
                stmt.setString(2, s);
                stmt.executeUpdate();
            }
            sendMailUpdatedUserInfo(u);
        } catch (SQLException e) {
            System.out.println("Feil i lagring av bruker: " + e);
        } finally {
            DatabaseHjelper.lukk(stmt);
            DatabaseHjelper.lukk(conn);
        }
    }

        private void sendMailUpdatedUserInfo(User u){
        String content = "Hei " + u.getFirstName() + " " + u.getLastName()
                +". Din brukerinformasjon hos Emner'R'Us er oppdatert."
                + "\n\nBrukernavn: " + u.getUserName() + "\nPassord: " + u.getPassword()
                + "\n\n Mvh GRPS-10\nSystemeringsprosjekt 2011";
        String subject = "Emner'R'Us brukerprofil oppdatert.";
        SendMail sM = new SendMail(u.getEmail(), content, subject);
        sM.run();
    }

    public String setNewPasswordFlagAndNavigate(User u) {
        u.setNewPasswordFlag(true);
        return "confirmNewPassword";
    }

    public String revertFlagsAndNavigate(){
        for(User u: users){
            if(u.isEditable()) u.setEditable(false);
            if(u.isDeleteFlag()) u.setDeleteFlag(false);
            if(u.isNewPasswordFlag()) u.setNewPasswordFlag(false);
        }
        return navToUserList();
    }

    public String executeNewPassord(){
        for (User u : users) {
            if (u.isNewPasswordFlag()) {
                newPassword(u);
                u.setNewPasswordFlag(false);
                break;
            }
        }
        return navToUserList();
    }

    private void newPassword(User u){
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = dbh.finnForbindelse();
            stmt = conn.prepareStatement("UPDATE users SET password=? WHERE userID=?");
            u.setPassword(RandomPassword.getRandomString(6));
            stmt.setString(1, u.getPassword());
            stmt.setInt(2, u.getUserID());
            stmt.executeUpdate();
            sendMailNewPassword(u);
        } catch (SQLException e) {
            System.out.println("Feil i lagring av bruker: " + e);
        } finally {
            DatabaseHjelper.lukk(stmt);
            DatabaseHjelper.lukk(conn);
        }
    }

    private void sendMailNewPassword(User u){
        String content = "Hei " + u.getFirstName() + " " + u.getLastName()
                +". Du har fått utstedt et nytt passord hos Emner'R'Us."
                + "\n\nBrukernavn: " + u.getUserName() + "\nPassord: " + u.getPassword()
                + "\n\n Mvh GRPS-10\nSystemeringsprosjekt 2011";
        String subject = "Emner'R'Us, nytt passord.";
        SendMail sM = new SendMail(u.getEmail(), content, subject);
        sM.run();
    }


    public String setDeleteFlagAndNavigate(User u) {
        u.setDeleteFlag(true);
        return "confirmDeleteUser";
    }


    public String executeDelete(){
        for (User u: users) {
            if (u.isDeleteFlag()) {
                deleteUser(u);
                users.remove(u);
                break;
            }
        }
        return navToUserList();
    }

    private void deleteUser(User u){
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = dbh.finnForbindelse();
            stmt = conn.prepareStatement("DELETE FROM users WHERE userID=?");
            stmt.setInt(1, u.getUserID());
            stmt.executeUpdate();
            sendMailDeletedUser(u);
        } catch (SQLException e) {
            System.out.println("Feil i sletting av bruker: " + e);
        } finally {
            DatabaseHjelper.lukk(stmt);
            DatabaseHjelper.lukk(conn);
        }
    }

    private void sendMailDeletedUser(User u){
        String content = "Hei " + u.getFirstName() + " " + u.getLastName()
                +". Din bruker, " + u.getUserName() + ", hos oss er slettet."
                + "\nVelkommen igjen senere. Ha en fin dag.."
                + "\n\n kthxbai\n\n mvh GRPS-10\nSystemeringsprosjekt 2011";
        String subject = "Emner'R'Us, din bruker er slettet.";
        SendMail sM = new SendMail(u.getEmail(), content, subject);
        sM.run();
    }



    public List<User> getUsers() {
        return users;
    }

}